package cn.myspringboot.template;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.myspringboot.config.WechatProperties;
import cn.myspringboot.domain.OpenIdResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class WechatLoginTemplate {

    private WechatProperties properties;

    public WechatLoginTemplate(WechatProperties properties) {
        this.properties = properties;
    }

    public OpenIdResult getOpenId(String code) {
        //1.获取到微信的OpenIdurl
        String OpenIdUrl = String.format(properties.getOpenidurl(), properties.getAppid(), properties.getAppsecret(), code);
        HttpResponse execute = HttpRequest.get(OpenIdUrl).execute();
        String body = execute.body();
        OpenIdResult openIdResult = JSON.parseObject(body, OpenIdResult.class);
        String phone = getWethatPhone(code);
        openIdResult.setPhone(phone);
        return openIdResult;
    }

    public String getTokenAccess() {
        String getTokenUrl = String.format(properties.getAccesstokenurl(),properties.getAppid(), properties.getAppsecret());
        HttpResponse execute = HttpRequest.get(getTokenUrl).execute();
        String body = execute.body();
        String accessToken = JSON.parseObject(body).get("access_token").toString();
        return accessToken;
    }

    private String getWethatPhone(String code) {
        String getPhoneUrl = String.format(properties.getPhonenumberurl(),getTokenAccess());
        HttpRequest post = HttpRequest.post(getPhoneUrl);
        //携带请求参数
        Map<String, Object> p = new HashMap<>();
        p.put("code",code);
        post.form(p);
        HttpResponse execute = post.execute();
        //得到结果
        String body = execute.body();
        //获取里面的token
        JSONObject jsonObject = JSON.parseObject(body);
        if(jsonObject.get("errmsg").toString().equals("ok")){
            return JSONObject.parseObject(
                    jsonObject.get("phone_info").toString()
            ).get("phoneNumber").toString();
        }
        return getRandomPhone();
    }


    private String getRandomPhone() {
        Random random = new Random();
        return String.valueOf(Math.abs(random.nextLong())).substring(0,11);
    }
}